package com.common;

import java.util.Arrays;
import java.util.Random;

/**
 * 随机类
 */
public class RandomUtils {

    public final static Random RANDOM = new Random();


    /**
     * 获取无重复随机序列
     * @param amount
     * @return
     */
    public static int[] getRandomSequence(int amount) {
        return getRandomSequence(amount, 0, amount);
    }

    /**
     * 获取无重复随机序列
     * @param amount
     * @return
     */
    public static int[] getRandomSequence(int amount, int min, int max) {
        if (max - min != amount) return null;
        int[] sequence = new int[amount];
        int[] output = new int[amount];
        for (int i = 0; i < amount; i++) {
            output[i] = i + min;
        }
        int index = amount;
        for (int i = 0; i < amount; i++) {
            int num = random(min, max--);
            sequence[i] = output[num - min];
            output[num - min] = output[--index];
        }
        return sequence;
    }

    /**
     * 从【min, max】区间中随机一个数字
     * @param min
     * @param max
     * @return
     */
    public static int random(int min, int max) {
        if (min > max) {
            int temp = min;
            max = min;
            min = temp;
        }
        return RANDOM.nextInt(max) % (max - min + 1) + min;
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        int[] sequence = getRandomSequence(10000, 10000, 20000);
        System.out.println(System.currentTimeMillis() - start);
        Sort.mergeSort(sequence, 0, sequence.length - 1);
        System.out.println(Arrays.toString(sequence));
        System.out.println(sequence.length);

    }
}
